<?php

require_once(OC_App::getAppPath('company') . "/lib/helper.php");
JLoader::register("PCompanyModelSubAccounts", OC_App::getAppPath('company') . "/lib/subaccounts.php");

$l = OC_L10N::get('company');
OCP\JSON::callCheck();

if(!PFactory::isMasterUser()) {
	OC_JSON::error(array('data' => array( 'message' => '您无权访问该资源')));
   exit;
}

$displayname = JRequest::getString("displayname", "");
$username = JRequest::getString("username", "");
$password = JRequest::getString("password", "", "post", JREQUEST_NOTRIM);
$note = JRequest::getString("note", "");
$permission = JRequest::getVar('permission', array(), '', 'array');
$assignedjobs = JRequest::getVar('assignedjobs', array(), '', 'array');

// Return Success story
try {
   if(!PSession::checkToken('post')) {
	   OC_JSON::error(array('data' => array( 'message' => '登录已失效，请重新登录')));
      exit;
   }
   
   $userQuota = PCompanyHelper::getUserQuota();
   if (!isDevMode() && $userQuota['num_subaccounts'] >= $userQuota['quota']['subaccount_max'] && PCompanyHelper::checkQuotaEnable()) {
      OC_JSON::error(array('data' => array( 'message' => '您的子账号数目已达上限，不能创建子账号')));
      return false;
   }
   
   $data = array();
   $data['uid'] = $username;
   $data['note'] = $note;
   
   if(!preg_match("/^[^\s]{6,255}$/i", JRequest::getString('password', "", "post", JREQUEST_NOTRIM))) {
      OC_JSON::error(array('data' => array( 'message' => '请输入有效的密码，至少6个字符，可包含数字、字母或其他字符，不允许使用空格')));
      exit();
   }
   $permissions = PERMISSION_VIEW_ALL | PERMISSION_VIEW_SHARED;
   if (!empty($permission)) {
      foreach ($permission as $p) {
         if ($p & PERMISSION_JOB_CRUD) {
            $permissions |= PERMISSION_JOB_CRUD;
         }
          
         if ($p & PERMISSION_JOB_ADMIN_ALL) {
            $permissions |= PERMISSION_JOB_ADMIN_ALL;
         }
          
         if ($p & PERMISSION_JOB_ADMIN_ASSIGNED) {
            $permissions |= PERMISSION_JOB_ADMIN_ASSIGNED;
         }
      }
   }
   $data['permissions'] = $permissions;
   
   $model = new PCompanyModelSubAccounts;

   if (!$model->isDeletedUser($username)) {
      if (!OC_User::createUser($username, $password)) {
         $model->removeUser($username);
      	OC_JSON::error(array('data' => array( 'message' => '保存用户失败！')));
      	exit();
      }
   	
      if (!$model->createUserExtended($data)) {
         $model->removeUser($username);
         OC_JSON::error(array('data' => array( 'message' => '创建用户失败！')));
         exit();
      }
   } else {
      $data['deleted'] = 0;
      if(!empty($password) && !OC_User::setPassword($username, $password)) {
         $model->removeUser($username);
         OC_JSON::error(array('data' => array( 'message' => '保存密码失败！')));
         exit();
      }
      
      if (!$model->updateUserExtended($data)) {
         $model->removeUser($username);
         OC_JSON::error(array('data' => array( 'message' => '创建用户失败！')));
         exit();
      }
   }

   OC_User::setDisplayName($username, $displayname);
   
   if (!$model->saveJobManager($username, $permissions, $assignedjobs)) {
      $model->removeUser($username);
      OC_JSON::error(array('data' => array( 'message' => $model->getError() ? $model->getError() : '系统错误')));
      exit();
   }

   /* send mail */
   require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
   $mailer = new JobmailModelEmail();
   $config = PFactory::getConfig();
   $user= PFactory::getMasterUser();
   $receiver = (isDevMode() || isTestMode() || isTestUser($user->email)) ? $config->get('employeremail', '') : $username; 
    
   $supportmail = $config->get('mailfrom','');
   $body = '<p class="p1"><b>' . $displayname . '，您好！</b></p>
               <p class="p3">您公司HR在枇杷派云招聘给您创建了登录账号，用于协助招聘。</p>
               <p class="p3">登录用户名是您的邮箱地址：<b>' . $username . '</b>，初始密码是：<b>' . $password . '</b></p>' ;

   $mailer->setTemplate('hrsimple');
   $mailer->setVariables(array(
                 'recipient'=>$receiver,
                 'fromName'=>'枇杷派云招聘',
                 'subject'=>'您在枇杷派云招聘的登录账号',
                 'supportmail'=>$supportmail,
                 'hrurl'=>'http://'.OC_Request::serverHost(),
                 'body'=>$body
         )
    );

   $mailer->send();
 
   OC_JSON::success();

} catch (Exception $exception) {
   OC_JSON::error(array("data" => array( "message" => $l->t($exception->getMessage()))));
}
